package org.rslai.util.process;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * 执行外部程序的 Windows 实现
 * @author rslai
 */
public class ProcessWindows extends AbstractProcess implements Process {

	@Override
	public int processExists(String process) throws IOException {
		String command;
		if (org.rslai.util.string.Verify.getInstance().isInteger(process)) {
			command = "tasklist /fi \"PID eq "+ process + "\"";
		} else {
			command = "tasklist /fi \"imagename eq "+ process + "\"";
		}

		String result = this.runWait(command);
		BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(result.getBytes())));
		String line; 
		while ((line = bufferedreader.readLine()) != null) {
			if (line.contains(process)) {
				bufferedreader.close();
				return new Integer(line.split("\\s{1,}")[1]);
			}
		}
		bufferedreader.close();

		return 0;
	}

	@Override
	public boolean processClose(String process) throws IOException {
		String command;
		if (org.rslai.util.string.Verify.getInstance().isInteger(process)) {
			command = "taskkill /F /PID "+ process;
		} else {
			command = "taskkill /F /IM "+ process;
		}

		String result = this.runWait(command);
		if (result.contains("PID")) {
			return true;
		} else {
			return false;
		}
	}

}
